import { type UseQueryResult, useQuery } from "@tanstack/solid-query";
import { RefreshCwIcon } from "lucide-solid";
import { Match, Switch } from "solid-js";
import { getJoke } from "@/apis/joke";
import Button from "@/components/Button";
import Panel from "@/components/Panel";

export default function JokeView() {
  const query = useQuery(() => ({
    queryKey: ["joke"],
    queryFn: async () => {
      const resp = await getJoke();
      if (resp.error) {
        throw new Error("Get joke failed");
      }
      return resp.joke;
    },
  }));

  return (
    <div class="max-w-md mx-auto mt-36">
      <Panel
        titleClass="justify-between"
        title={
          <>
            Joke
            <Button size="sm" shape="circle" onClick={() => query.refetch()}>
              <RefreshCwIcon />
            </Button>
          </>
        }
      >
        <QueriedJoke {...query} />
      </Panel>
      <div class="mt-6 flex justify-end">
        <a href="https://jokeapi.dev/" target="__blank">
          About jokeapi.
        </a>
      </div>
    </div>
  );
}

function QueriedJoke(query: UseQueryResult<string, Error>) {
  return (
    <Switch fallback={<div>{query.data}</div>}>
      <Match when={query.status === "pending" || query.fetchStatus === "fetching"}>
        <div>Loading...</div>
      </Match>
      <Match when={query.status === "error"}>
        <div>Error: {query?.error?.message}</div>
      </Match>
    </Switch>
  );
}
